var rootPath = '';//kk.getRootPath();

/* bookCatDom */
var bookCatDom = '\
<div class="box box-skin-inner sub-content">\
	<div class="box-header with-border">\
		<span class="box-title"></span>\
		<div class="box-tools pull-right">\
			<button type="button" class="btn btn-box-tool btnCancel" data-widget="remove"><i class="fa fa-times"></i></button>\
		</div>\
	</div>\
	<div class="box-body">\
		<div class="row">\
			<form class="form-horizontal" id="bookCatForm">\
			<div class="col-sm-7">\
				<div class="form-group">\
					<label for="myFile" class="col-sm-2 control-label">图片</label>\
					<div class="col-sm-10">\
						<input type="file" id="myFile" name="file" />\
						<input type="hidden" id="pic" name="pic" />\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="name" class="col-sm-2 control-label">名称<span class="text-red">*</span></label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="name" name="name" placeholder="名称">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="pidName" class="col-sm-2 control-label">父节点</label>\
					<div class="col-sm-10">\
						<div class="input-group">\
							<input type="hidden" id="pid" name="pid">\
						    <input type="text" class="form-control" id="pidName" name="pidName" disabled>\
							<span class="input-group-btn">\
								<button type="button" class="btn btn-info btn-flat" onclick="showMenu();">选择</button>\
							</span>\
						</div>\
						<div id="menuContent" class="menuContent" style="display:none; position:absolute; background-color: #f4f4f4; z-index: 4002;">\
							<ul id="parentTree" class="ztree"></ul>\
						</div>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="url" class="col-sm-2 control-label">访问链接</label>\
					<div class="col-sm-10">\
						<input type="text" class="form-control" id="url" name="url" placeholder="访问链接">\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="description" class="col-sm-2 control-label">简介</label>\
					<div class="col-sm-10">\
						<textarea class="form-control" rows="6" id="description" name="description" placeholder="简介"></textarea>\
					</div>\
				</div>\
				<div class="form-group">\
					<label for="extInfo" class="col-sm-2 control-label">背景颜色</label>\
					<div class="col-sm-10">\
						<div class="input-group my-colorpicker2">\
							<input type="text" class="form-control" id="extInfo" name="ext_info" placeholder="背景颜色">\
							<div class="input-group-addon">\
								<i></i>\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>\
			<div class="col-sm-5">\
				<div class="foo">\
					<p class="text-muted">1. 图片的尺寸为800*450</p>\
					<p class="text-muted">2. 标题根据页面是否显示而确定是否需要填入</p>\
					<p class="text-muted">3. 背景颜色主要用于轮播图片</p>\
					<p class="text-muted">4. 排序越小，实际显示越靠前</p>\
					<p class="text-muted">5. 链接地址可填入本系统的网站或课程链接地址（格式为wx/<path>.do）或其它任意可访问网址</p>\
					<p class="text-muted">6. 图片说明根据页面是否显示而确定是否需要填入</p>\
				</div>\
			</div>\
			<div class="rm-or-hide">\
				<input type="hidden" name="id" />\
			</div>\
			</form>\
		</div>\
	</div>\
	<div class="box-footer text-center">\
		<button type="button" class="btn btn-info btn-flat btnOK">确定</button>\
		<button type="button" class="btn btn-default btn-flat btnCancel">取消</button>\
	</div>\
</div>\
';

/* CRUD 1: Create, 2: Read, 3: Update, 4: Delete */
var CREATE = 1, READ = 2, UPDATE = 3, DELETE = 4;
function CRUDBookCatFunc(operCode, id, index) {
	var canOpen = false;
	var url;
	var obj;
	
	if (operCode == CREATE) {
		canOpen = true;
	} else if (operCode == READ || operCode == UPDATE) {
		url = rootPath + '/Book/BookCat/find?id=' + id;
		obj = kk.getObj(url);
		if (obj != null) {
			canOpen = true;
		}
	} else if (operCode == DELETE) {
		url = rootPath + '/Book/BookCat/delete?id=' + id;
		kk.deleteObj(url, '#table');
	} else {
		return false;
	}
	
	if (!canOpen) {
		return false;
	}
		
	$('.main-content').hide();
	$('.main-content').after(bookCatDom);
	
	var xqu = xqupload('#myFile', {
		uploadUrl			: rootPath + '/Asset/Upload/upload?savePath=book_cat_pic',
        recvObj				: '#pic'
    });
	
	if (operCode == CREATE) {
		$('.box-title').empty().append('添加');

		initTree();
    	xupload('#myFile', {
    		height: 220,
    		changeHandler: function($this) {
    			$('#pic').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/contents/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});

		$('.rm-or-hide').remove();
	} else if (operCode == READ) {
		$('.box-title').empty().append('查看');
		$('.btnOK').hide();
		$('.btnCancel').text('关闭');

		$('#bookCatForm').setForm(obj);
		initTree(obj.id, obj.cid);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.pic,
    		isDisabled: true
    	});

		$('#bookCatForm').find(':input').attr("disabled", "disabled");		// 习惯性地处理
	} else if (operCode == UPDATE) {
		$('.box-title').empty().append('编辑');
		
		$('#bookCatForm').setForm(obj);
		initTree(obj.id, obj.cid);
    	xupload('#myFile', {
    		height: 220,
    		defaultFile: rootPath + '/' + obj.pic,
    		changeHandler: function($this) {
    			$('#pic').val('');
    			
    			lrz($('#myFile')[0].files[0], {width: 450, quality: 0.8}).then(function (rst) {
    	            // 处理成功会执行
    	            console.log(rst);
    	            $this.setFile(rst.base64);
        			
        			var filename = $('#myFile').val();
        		    var fileExt = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';			// fileExt
        		    var key = kk.getProjectName() + '/contents/' + new Date().format("yyMMddhhmmssS") + kk.mathRand(1) + '.' + fileExt;
        			xqu.upload(rst.formData, key);
    	        }).catch(function (err) {
    	            // 处理失败会执行
    	        }).always(function () {
    	            // 不管是成功失败，都会执行
    	        });
    		}
    	});
    	
		$('.rm-or-hide').hide();
	}
	
	$(".my-colorpicker2").colorpicker();
	
	validator = $("#bookCatForm").validate({
		onfocusout: function(element) {
			$(element).valid();
		},
        rules: {
			name: "required",
			pid: "required",
        },
        messages: {
			name: "请输入名称",
			pid: "请输入pid",
        }
    });
	
	$('.btnOK').off('click').on('click', function() {
 		if (validator.form() && doCU(operCode, id, index)) {
			$('.sub-content').remove();
			$('.main-content').show();
 		}
	});
	
	$('.btnCancel').off('click').on('click', function() {
		xqu.abort();
		
		$('.sub-content').remove();
		$('.main-content').show();
	});
}

/* Create & Update */
function doCU(operCode, id, index) {
    var url;
    var method;
    var jsonObj = $('#bookCatForm').serializeObject();
	var jsonStr = JSON.stringify(jsonObj);
//console.log('jsonStr = ' + jsonStr);
	var result;
	
	if (operCode == CREATE) {
	 	url = rootPath + '/Book/BookCat/save';
		method = "POST";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	} else if (operCode == UPDATE) {
	 	url = rootPath + '/Book/BookCat/update?id=' + id;
		method = "PUT";
		result = kk.doStrAjax(url, method, jsonStr);
		
	    if (result.code == 0) {
        	xtt.refresh();

	    	return true;
		}
	}
	
	return false;
}


/****** tree ******/
/* init tree */
function initTree(id, pid) {
	pid = pid === undefined ? 0 : pid;					// pid <==> 0
	
	var setting = {
		async: {
			enable: true,
			type: "get",
			url: rootPath + '/Book/BookCat/getAll',
			autoParam: ["id", "name"],
			dataFilter: ajaxDataFilter
		},
		callback: {
			onClick: onClick,
			onAsyncSuccess: zTreeOnAsyncSuccess
		}, 
		data: {
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "pid",
				rootPId: 0
			},
			key: {
	            url: "xUrl"
	        }
		}
	};
	
	function ajaxDataFilter(treeId, parentNode, responseData) {
		var newData = new Array();
		var rootData = {
			id: 0,
			pid: -1,
			name: '根元素'
		};
		newData.push(rootData);
		
		var data = responseData.obj;
		for (var i = 0; i < data.length; i++) {
			if (data[i].id != id && data[i].pid != id) {
				newData.push(data[i]);
			}
		}
		
	    return newData;
	}
	
	function onClick(e, treeId, treeNode) {
		$('#pidName').val(treeNode.name);
		$('#pid').val(treeNode.id);
		return false;
	}
	
	function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {		// 加载成功后赋值
		var node = zTreeObj.getNodeByParam("id", pid);
		$('#pidName').val(node.name);
	}

	zTreeObj = $.fn.zTree.init($("#parentTree"), setting);
}

/* batRefreashBookCatFunc */
function batRefreashBookCatFunc() {
	var xloading = xpopup.loading();
	
   	$.ajax({
   		type: 'PUT',
   		url: rootPath + '/Book/BookCat/batRefreash',
   		data: null,
        dataType: 'json',
       	success: function(data) {
       		xloading.destroy();
       		
       		if (data.code == 0) {
       			xtt.refresh();

		   		xpopup.notify({
		           	style: 'mini',
		           	type: 'success',
//		           	title: '操作成功',
   	                msg: data.msg,
					delay: 1000,
					position: 'center',
				});
   			}
       	}
   	});
}
